<?php
/**
 * Created by PhpStorm.
 * User: PhpZhi
 * Date: 2019/11/2 16:58
 * Note: api 商品模型
 */

namespace app\api\model\goods;

use app\common\model\goods\Goods as GoodsModel;
use app\common\model\goods\GoodsSpec;

class Goods extends GoodsModel
{
    public $hidden = [
        'sales_actual',
        'sales_initial',
    ];

    public $append = [
        'goods_sales'
    ];

    /**
     * @param $goodsId
     * @return bool
     * @throws \think\Exception
     */
    public static function isValidGoods($goodsId)
    {
        return self::be(['id' => $goodsId, 'is_del' => 0, 'status' => 1]) > 0;
    }

    /**
     * 查询一条数据是否存在
     * @param $map
     * @param string $field
     * @return bool
     * @throws \think\Exception
     */
    public static function be($map, $field = '')
    {
        $model = (new self);
        if (!is_array($map) && empty($field)) $field = $model->getPk();
        $map = !is_array($map) ? [$field => $map] : $map;
        return 0 < $model->where($map)->count();
    }

    /**
     * 获取库存
     * @param $goodsId
     * @param $goodsSkuId
     * @return mixed
     */
    public static function getGoodsStock($goodsId, $goodsSkuId)
    {
        $model = new GoodsSpec();
        return $model->field(['goods_spec_id,goods_id,stock_num'])
            ->where(['goods_id' => $goodsId, 'spec_sku_id' => $goodsSkuId])
            ->value('stock_num');
    }

    public static function findOne($id)
    {
        return self::with(['spec' => function ($query) use ($id) {
            $query->where(['goods_id' => $id])->find();
        }])->where(['id' => $id])->select();
    }

    /**
     * 获取一条完整的商品数据
     * @param $id
     * @param $spec_sku_id
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getGoodsSpec($id, $spec_sku_id)
    {
        $model = new GoodsSpec();
        return $model->field('goods_id,spec_sku_id,goods_spec_id')
            ->where(['goods_id' => $id, 'spec_sku_id' => $spec_sku_id])
            ->find();
    }
}